package com.yumo.kangchenjunga.coupon.v1;

import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.ExampleMatcher.StringMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.querydsl.core.types.dsl.BooleanExpression;

@Service
public final class CouponLogService {

	@Autowired
	private CouponLogRepository repository;

	public Page<CouponLogEntity> page(Pageable pageable) {
		return repository.findAll(pageable);
	}

	public Page<CouponLogEntity> query(CouponLogEntity couponLog, Pageable pageable) {
		ExampleMatcher matcher = ExampleMatcher.matchingAll().withIgnoreCase().withIgnorePaths("id")
				.withStringMatcher(StringMatcher.CONTAINING);
		Example<CouponLogEntity> example = Example.of(couponLog, matcher);

		return repository.findAll(example, pageable);
	}

	public Page<CouponLogEntity> query(Integer activityId, Integer companyId, LocalDate startDate, LocalDate endDate,
			Pageable pageable) {
		QCouponLogEntity log = QCouponLogEntity.couponLogEntity;
		BooleanExpression exp = log.op.eq("redeem").and(log.opResult.eq("success"));

		if (activityId != null) {
			exp = exp.and(log.activityId.eq(activityId));
		}

		if (companyId != null) {
			exp = exp.and(log.companyId.eq(companyId));
		}

		if (startDate != null) {
			exp = exp.and(log.opTime.goe(startDate.atStartOfDay(ZoneOffset.UTC).toInstant()));
		}

		if (endDate != null) {
			exp = exp.and(log.opTime.lt(endDate.plusDays(1).atStartOfDay(ZoneOffset.UTC).toInstant()));
		}

		return repository.findAll(exp, pageable);
	}

	public void saveLog(CouponLogEntity log) {
		repository.save(log);
	}

	public void saveLogs(Collection<CouponLogEntity> logs) {
		repository.saveAll(logs);
	}

}
